package com.example.neutonote2.utils;

import android.util.Log;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 调试工具类
 */
public class DebugUtils {
    private static final String TAG = "DebugUtils";
    
    /**
     * 测试网络连接
     * @param url 要测试的URL
     * @return 连接结果
     */
    public static String testConnection(String url) {
        try {
            if (url == null || url.isEmpty()) {
                Log.e(TAG, "测试连接失败: URL为空");
                return "无效URL";
            }
            
            Log.d(TAG, "测试连接: " + url);
            
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)  // 缩短超时时间以便快速失败
                    .readTimeout(5, TimeUnit.SECONDS)
                    .build();
                    
            Request request = new Request.Builder()
                    .url(url)
                    .head()  // 使用HEAD请求代替GET，减少数据传输
                    .build();
            
            try {
                Response response = client.newCall(request).execute();
                int code = response.code();
                String message = response.message();
                Log.d(TAG, "连接响应: " + code + " " + message);
                response.close();  // 确保关闭响应
                
                return "连接状态: " + code + " " + message;
            } catch (java.net.UnknownHostException e) {
                Log.e(TAG, "未知主机: " + e.getMessage(), e);
                return "找不到服务器: " + e.getMessage();
            } catch (java.net.SocketTimeoutException e) {
                Log.e(TAG, "连接超时: " + e.getMessage(), e);
                return "连接超时: " + e.getMessage();
            } catch (java.io.IOException e) {
                Log.e(TAG, "IO异常: " + e.getMessage(), e);
                return "IO异常: " + e.getMessage();
            }
        } catch (Exception e) {
            Log.e(TAG, "连接测试失败: " + e.getMessage(), e);
            return "连接失败: " + e.getMessage();
        }
    }
} 